package me.greyliu.kuai.service;

import jakarta.servlet.http.HttpServletResponse;
import me.greyliu.kuai.dao.ShareDao;
import me.greyliu.kuai.entity.Response;
import me.greyliu.kuai.entity.Share;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Service
public class FTPService {
    private FTPClient ftpClient=null;
    ShareDao shareDao=new ShareDao();
    public void connect(FTPClient ftpClient) throws IOException {
        try {
            ftpClient.setControlEncoding("GBK");
            ftpClient.connect("127.0.0.1", 21);
            ftpClient.login("Anonymous", "");
            System.out.println("FTP连接成功");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.abort();
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public FTPService() {
        this.ftpClient = new FTPClient();
        try {
            connect(ftpClient);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public FTPFile[] listFile(String path)  {
        try {
            return ftpClient.listFiles(path);
        } catch (IOException e) {
            try {
                connect(ftpClient);
                return ftpClient.listFiles(path);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    public void download(HttpServletResponse response,String ftpPath, String ftpFileName)  {
        try {
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(ftpFileName,"UTF-8"));
            ftpClient.retrieveFile(ftpPath+"/"+ftpFileName, response.getOutputStream());
            System.out.println(ftpPath+"/"+ftpFileName+"-下载完成");
        } catch (IOException e) {
            try {
                connect(ftpClient);
                download(response,ftpPath,ftpFileName);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    public Response upload(MultipartFile file,String location){
        try {
            String fileName = file.getOriginalFilename();
            Path path = Paths.get(fileName);
            File tempFile = path.toFile();
            // 将MultipartFile内容写入临时文件
            file.transferTo(tempFile);
            FileInputStream input = new FileInputStream(tempFile);
            ftpClient.changeWorkingDirectory(location);
            ftpClient.storeFile(tempFile.getName(), input);
            ftpClient.changeWorkingDirectory("/");
            input.close();
            System.out.println(tempFile.getPath()+"上传成功");
            return new Response(202,"上传成功");
        } catch (IOException e) {
            try {
                connect(ftpClient);
                return upload(file,location);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    public void getShare(HttpServletResponse response, String id, String pwd) {
        try {
        Share share=shareDao.getShareByID(id);
        if(share==null){
            response.setContentType("text/plain");
            response.setCharacterEncoding("utf8");
            response.getWriter().write("文件不存在");
        }else if(!pwd.equals(share.getPwd())){
            response.setContentType("text/plain");
            response.setCharacterEncoding("utf8");
            response.getWriter().write("密码错误");
        }else{
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(share.getName(),"UTF-8"));
            ftpClient.retrieveFile(share.getPath()+"/"+share.getName(), response.getOutputStream());
            System.out.println(share.getPath()+"/"+share.getName()+"-下载完成");
        }}catch (IOException e) {
            try {
                connect(ftpClient);
                getShare(response,id,pwd);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
